package cn.gray.gae.job.daily.server;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import cn.gray.gae.job.daily.client.GreetingService;
import cn.gray.gae.job.daily.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to the client.
			throw new IllegalArgumentException("Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

//		UserService userService = UserServiceFactory.getUserService();
//		User user = userService.getCurrentUser();
//
//		if (user == null) {
//			String s = userService.createLoginURL("/Graydailyjob.html");
//			return s;
//		}
//
//		String r = user.getEmail();
//
//		List<AccountDomain> accs = DaoUtil.getAll(AccountDomain.class);
//		if (accs == null || accs.isEmpty()) {
//			initData();
//			r = r + ">>>0";
//		} else {
//			r = r + ">>>" + accs.size();
//		}

		HttpClient c = new HttpClient();
		GetMethod g = new GetMethod("https://coinad.com/?a=Account");
		try {
			c.executeMethod(g);
			return g.getResponseBodyAsString();
		} catch (Throwable t) {
			return  "<<<<br>Hello, " + input + "!<br><br>I am running " + serverInfo
					+ ".<br><br>It looks like you are using:<br>" + userAgent;
		}
	}

	private void initData() {
		// AccountDomain acc = new AccountDomain();
		// acc.setEmail("long1795@gmail.com");
		// acc.setScop("coinAD");
		// acc.setAccount("zzjhacn");
		// acc.setAdViewedCnt(1);
		// acc.setBalance("2");
		// acc.setBtcAddres("add");
		// DaoUtil.add(acc);
	}

	/**
	 * Escape an html string.
	 * Escaping data received from the client helps to prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}
}
